<template>
  <div class="subway-manager">
    <div class="manager-header">
      <h3>地铁线路管理</h3>
      <el-button type="primary" size="small" @click="showAddLineDialog"
        >添加线路</el-button
      >
    </div>

    <div class="line-list">
      <el-empty v-if="lines.length === 0" description="暂无线路数据" />
      <div v-else class="line-item" v-for="line in lines" :key="line.name">
        <div class="line-info">
          <div
            class="line-color"
            :style="{ backgroundColor: line.color }"
          ></div>
          <span class="line-name">{{ line.name }}</span>
        </div>
        <div class="line-actions">
          <el-switch
            v-model="line.show"
            @change="(val) => toggleLineVisibility(line.name, val)"
            active-color="#13ce66"
            inactive-color="#ff4949"
          >
          </el-switch>
          <el-button
            type="danger"
            size="small"
            icon="Delete"
            circle
            @click="removeLine(line.name)"
          ></el-button>
        </div>
      </div>
    </div>

    <!-- 添加线路对话框 -->
    <el-dialog
      v-model="addLineDialogVisible"
      title="添加地铁线路"
      width="500px"
    >
      <el-form :model="newLine" label-width="100px">
        <el-form-item label="线路名称">
          <el-input v-model="newLine.name" placeholder="例如：1号线"></el-input>
        </el-form-item>
        <el-form-item label="线路颜色">
          <el-color-picker v-model="newLine.color"></el-color-picker>
        </el-form-item>
        <el-form-item label="站点数据">
          <el-upload
            action=""
            :auto-upload="false"
            :on-change="handleFileChange"
            :limit="1"
            accept=".json,.geojson"
          >
            <el-button type="primary">选择GeoJSON文件</el-button>
            <template #tip>
              <div class="el-upload__tip">
                请上传包含站点和线路数据的GeoJSON文件
              </div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addLineDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="addLine" :disabled="!isFormValid">
            确认
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { useLineData } from '@/store'
import { ElMessage, ElMessageBox } from 'element-plus'

const store = useLineData()
const lines = computed(() => store.getLines || [])

// 新线路表单数据
const addLineDialogVisible = ref(false)
const newLine = ref({
  name: '',
  color: '#409EFF',
  show: true,
  stations: [],
  coordinates: [],
})
const fileData = ref(null)

// 表单验证
const isFormValid = computed(() => {
  return newLine.value.name && fileData.value
})

// 显示添加线路对话框
const showAddLineDialog = () => {
  addLineDialogVisible.value = true
  newLine.value = {
    name: '',
    color: '#409EFF',
    show: true,
    stations: [],
    coordinates: [],
  }
  fileData.value = null
}

// 处理文件上传
const handleFileChange = (file) => {
  const reader = new FileReader()
  reader.onload = (e) => {
    try {
      const data = JSON.parse(e.target.result)
      fileData.value = data
      ElMessage.success('文件解析成功')
    } catch (error) {
      ElMessage.error('文件格式错误，请上传有效的GeoJSON文件')
      fileData.value = null
    }
  }
  reader.readAsText(file.raw)
}

// 添加线路
const addLine = () => {
  if (!isFormValid.value) {
    ElMessage.warning('请填写完整的线路信息')
    return
  }

  try {
    // 从GeoJSON中提取站点和线路数据
    const lineData = processGeoJSON(fileData.value)

    // 创建新线路对象
    const line = {
      name: newLine.value.name,
      color: newLine.value.color,
      show: newLine.value.show,
      stations: lineData.stations,
      coordinates: lineData.coordinates,
    }

    // 添加到store
    store.addLine(line)

    ElMessage.success(`${line.name}添加成功`)
    addLineDialogVisible.value = false
  } catch (error) {
    ElMessage.error(`添加线路失败: ${error.message}`)
  }
}

// 处理GeoJSON数据
const processGeoJSON = (geoJSON) => {
  const stations = []
  let coordinates = []

  try {
    // 处理GeoJSON格式数据
    if (geoJSON.type === 'FeatureCollection') {
      geoJSON.features.forEach((feature) => {
        if (feature.geometry.type === 'Point') {
          // 站点数据
          stations.push({
            name: feature.properties.name || `站点${stations.length + 1}`,
            position: feature.geometry.coordinates,
          })
        } else if (feature.geometry.type === 'LineString') {
          // 线路数据
          coordinates = feature.geometry.coordinates
        }
      })
    }

    return { stations, coordinates }
  } catch (error) {
    throw new Error('GeoJSON数据格式不正确')
  }
}

// 切换线路显示状态
const toggleLineVisibility = (lineName, isVisible) => {
  store.updateLineVisibility(lineName, isVisible)
}

// 删除线路
const removeLine = (lineName) => {
  ElMessageBox.confirm(`确定要删除${lineName}吗？`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      store.removeLine(lineName)
      ElMessage.success(`${lineName}已删除`)
    })
    .catch(() => {})
}
</script>

<style scoped>
.subway-manager {
  position: absolute;
  top: 20px;
  right: 20px;
  width: 300px;
  background-color: rgba(255, 255, 255, 0.9);
  border-radius: 8px;
  padding: 15px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  z-index: 100;
}

.manager-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.manager-header h3 {
  margin: 0;
}

.line-list {
  max-height: 300px;
  overflow-y: auto;
}

.line-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 0;
  border-bottom: 1px solid #eee;
}

.line-info {
  display: flex;
  align-items: center;
}

.line-color {
  width: 16px;
  height: 16px;
  border-radius: 50%;
  margin-right: 10px;
}

.line-actions {
  display: flex;
  align-items: center;
  gap: 10px;
}
</style>
